/**
 * 工具类
 */
;(function () {
    if (!window.PM) {
        window.PM = {};
    }
    PM = {
        getURLParameter: function (paramName) {
            var hashString = window.location.search.substring(1),
                i, val, params = hashString.split("&");
            for (i = 0; i < params.length; i++) {
                val = params[i].split("=");
                if (val[0] == paramName) {
                    return unescape(val[1]);
                }
            }
            return null;
        },
        fnRequestAjax: function (url, data, type, successfn, errorfn) {
            type = (type == null || type == "" || typeof(type) == "undefined") ? "post" : type;
            data = (data == null || data == "" || typeof(data) == "undefined") ? "" : data;
            if (type == "post") {
                data = JSON.stringify(data);
            }
            var strToken = "";
            if (getCookie("_token")) {
                strToken = "Bearer " + getCookie("_token");
            }
            $.ajax({
                type: type,
                async: true,
                data: data,
                url: url,
                crossDomain: true,
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                xhrFields: {
                    withCredentials: false
                },
                headers: {
                    'Authorization': strToken
                },
                success: function (response) {
                    if ( response.status_code ) {
                        $.warningModal({
                            type: 'alert',
                            content: response.message
                        });
                    } else {
                        successfn(response);
                    }
                },
                error: function (response) {
                    try {
                        var data = JSON.parse(response.responseText);
                        if (response.status === 422) {
                            for (var error in data['errors']) {
                                var message = data['errors'][error][0];
                                break;
                            };
                        } else {
                            var message = data['message'];
                        }
                        $.warningModal({
                            type:'alert',
                            content:message,
                            confirm:function(){}
                        });
                    } catch (e) {
                        $.warningModal({
                            type:'alert',
                            content: '网络错误，请稍后重试',
                            confirm:function(){}
                        });
                    }
                },
                complete: function (response) {

                }
            });
        },
        fnRequestAjaxNoAsync: function(url, data, type, successfn, errorfn) {
            type = (type==null || type=="" || typeof(type)=="undefined")? "post" : type;
            data = (data==null || data=="" || typeof(data)=="undefined")? "" : data;
            if(type == "post"){
                data=JSON.stringify(data);
            }
            var strToken = "";
            if ( getCookie("_token") ) {
                strToken= "Bearer " + getCookie("_token");
            }
            $.ajax({
                type: type,
                async: false,
                data: data,
                url: url,
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                xhrFields: {
                    withCredentials: false
                },
                headers: {
                    'Authorization': strToken
                },
                success: function(response){
                    successfn(response);
                },
                error: function(response) {
                    try {
                        var data = JSON.parse(response.responseText);
                        if (response.status === 422) {
                            for (var error in data['errors']) {
                                var message = data['errors'][error][0];
                                break;
                            };
                        } else {
                            var message = data['message'];
                        }
                        $.warningModal({
                            type:'alert',
                            content:message,
                            confirm:function(){}
                        });
                    } catch (e) {
                        $.warningModal({
                            type:'alert',
                            content: '网络错误，请稍后重试',
                            confirm:function(){}
                        });
                    }
                },
                complete: function (response) {

                }
            });
        }
    };
})(window);

//设置cookie
function setCookie(cookiename, cookievalue, days) {
    var date = new Date();
    date.setTime(date.getTime() + Number(days) * 24 * 3600 * 1000);
    document.cookie = cookiename + "=" + escape(cookievalue) + "; path=/;expires = " + date.toGMTString();
}

//获取cookie
function getCookie(cookiename) {
    var nameEQ = cookiename + "=";
    var ca = document.cookie.split(';');    //把cookie分割成组
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];                      //取得字符串
        while (c.charAt(0) == ' ') {          //判断一下字符串有没有前导空格
            c = c.substring(1, c.length);      //有的话，从第二位开始取
        }
        if (c.indexOf(nameEQ) == 0) {       //如果含有我们要的name
            return unescape(c.substring(nameEQ.length, c.length));    //解码并截取我们要值
        }
    }
    return false;
}

//删除cookie中所有定变量函数
function delAllCookie() {
    var myDate = new Date();
    myDate.setTime(-1000);//设置时间
    var data = document.cookie;
    var dataArray = data.split("; ");
    for (var i = 0; i < dataArray.length; i++) {
        var varName = dataArray[i].split("=");
        document.cookie = varName[0] + "=''; expires=" + myDate.toGMTString();
    }

}
//设置头信息
function setheader(tk) {
    var token = getCookie(tk);
    if (token) {
        $.ajaxSetup({
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + token);
            }
        });
    } else {
        location.href = "/"
    }
}
//邮箱校验
function checkEmail(email) {
    var reg = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
    if (email.length == 0) {
        return false;
    } else {
        if (reg.test(email)) {
            return false;
        } else {
            return true;
        }
    }
}

//手机号码校验
function checkMobile(el) {
    var mobile = $.trim($(el).val());
    if (!mobile) {
        $(el).siblings(".error-hit").show().html(confirmMsg.mobileNull).addClass("data_warning");
        return false;
    } else {
        if (!/^((1[3,4,5,7,8][0-9]{1})+\d{8})$/.test(mobile)) {
            $(el).siblings(".error-hit").show().html(confirmMsg.mobileError).removeClass("data_warning").addClass("data_danger");
            return false;
        } else {
            $(el).siblings(".error-hit").hide();
            return true;
        }
    }
}

//手机号码校验
function checkMobileOrCall(mobile) {
    if (!/(\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/.test(mobile)) {
        return false;
    } else {
        return true;
    }
}

function checkNumber(e) {
    var key = window.event ? e.keyCode : e.which;
    var keychar = String.fromCharCode(key);
    reg = /\d/;
    var result = reg.test(keychar);
    if(!result){
        el.className = "warn";
        msg.innerHTML = "只能输入数字";
    }else{
    }
}

function isPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

var browser = {
    versions: function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {//移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
        };
    }(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
};

function isMobile() {
    if (browser.versions.mobile || browser.versions.ios || browser.versions.android ||
        browser.versions.iPhone || browser.versions.iPad) {
        return true;
    } else {
        return false;
    }
}

function formatDate(date, fmt) {
    var o = {
        "M+": date.getMonth() + 1,                 //月份
        "d+": date.getDate(),                    //日
        "h+": date.getHours(),                   //小时
        "m+": date.getMinutes(),                 //分
        "s+": date.getSeconds(),                 //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds()             //毫秒
    }

    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
//检验学校简称只能是数字和字母
function checkSchoolShortName(el) {
    var name = $.trim($(el).val());
    var jgpattern = /^[A-Za-z0-9]+$/;
    if (!name) {
        $(el).siblings(".error-hit").show().html(confirmMsg.shortNameNull).addClass("data_warning");
        return false;
    }
    else {
        if (!jgpattern.test(name)) {
            $(el).siblings(".error-hit").show().html(confirmMsg.schoolShortName).removeClass("data_warning").addClass("data_danger");
            return false;
        } else {
            $(el).siblings(".error-hit").hide();
            return true;
        }
    }
}
